import datetime

import django
from django.utils import timezone
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django import views
# Create your views here.
from Book_exaln_system.models import ExaminationForPeople, Examination
from Choose_coach_system.models import ChooseCoach, Blacklist, teacher_leave
from login_system.models import User
from djangoProject1 import settings
from django.middleware.csrf import get_token
from django.views.decorators.clickjacking import xframe_options_sameorigin

def get_new_coach():
    t = datetime.date.day

    if (settings.Last_Choose_Time is None) or (settings.Last_Choose_Time != t):
        print(settings.Last_Choose_Time, t)
        settings.Last_Choose_Time = t
        import random
        query = User.objects.filter(identity_c='1').all()
        for i in query:
            i.driving_license_type = random.choice([u'c1', u'c2'])
            i.save()

        for i in ChooseCoach.objects.filter().all():
            i.time_out = True
            i.save()


class chooseCoach(views.View):

    def get(self, request):
        get_new_coach()
        query = User.objects.filter(identity_c='1').all()
        return render(request, 'choose_coach/index.html',
                      context={'user': request.user, 'query': query,
                               'csrf_token': get_token(request), 't_dt': settings.train_time, 'blist': Blacklist,
                               'len': len, 'tl': teacher_leave, 'tz': timezone})

    def post(self, request):
        print(request.POST)
        t = User.objects.filter(username=request.POST.get('username')).first()
        if not t:
            return JsonResponse({'error': 'data error'})
        tm = timezone.now()
        msg = ChooseCoach.objects.filter(student=request.user, time_out=False)
        sql_t = str(tm.year) + '-' + str(tm.month) + '-' + (str(tm.day)) + ' ' + \
                request.POST.get('time').split(',')[0] + ':00:00'
        print(sql_t)
        sql_t = datetime.datetime(tm.year, tm.month, tm.day, int(request.POST.get('time').split(',')[0]), 00, 00) + datetime.timedelta(days=1)

        if msg:
            i = False
            for j in msg:
                if not j.drop_class:
                    i = not i
                if i:
                    return JsonResponse({'error': 'you has an appointment'})

        data = ChooseCoach.objects.filter(teacher=t, time_out=False, train_time=sql_t).all()
        if len(data) >= 3:
            return JsonResponse({'error': 'The coach is busy and full'})
        else:

            ChooseCoach.objects.create(
                teacher=t,
                student=request.user,
                train_time=sql_t,
            )
            return JsonResponse({'error': None, 'data': 'Choose success'})

@xframe_options_sameorigin
def cancel(request):
    try:
        ChooseCoach.objects.filter(id=request.POST.get('id')).first().delete()
        Blacklist.objects.create(
            student=request.user,
            teacher=User.objects.filter(username=request.POST.get('t_uname')).first()
        )
        return HttpResponse('Cancel the success')
    except Exception as e:
        return HttpResponse('Cancel the failure，error:' + str(e))


def root_cancel(request):
    data = ChooseCoach.objects.filter(id=request.POST.get('id')).first()
    data.drop_class = request.POST.get('sub')
    data.save()
    return HttpResponse('Cancel the success')


def get_statistics(req):
    if req.user.identity_c == '1':
        try:
            stud_li = []
            for i in ChooseCoach.objects.filter(teacher=req.user).all():
                if i.student.username in stud_li:
                    continue
                stud_li.append(i.student.username)
            print(stud_li)
            acc = [0, 0, 0, 0]
            for j in range(4):
                for i in stud_li:
                    stu = ExaminationForPeople.objects.filter(student=User.objects.filter(username=i).first(),
                                                              exaln__examination_type=j + 1).first()

                    if stu and stu.sbj_pass:
                        acc[j] += 1
                acc[j] ="%.2f"%(acc[j] / len(stud_li)*100)+ "%" if len(stud_li) != 0 else None

            return JsonResponse({'data': acc})

        except Exception as e:
            return HttpResponse('error:' + str(e))
    else:
        return HttpResponse('error')


def cancel_teacher_day(request):
    user = request.user
    if len(teacher_leave.objects.filter(teacher=user, date__month=timezone.now().date().month)) == 3:
        return HttpResponse('<script>alert("leave is full !"); window.history.go(-1)</script>')
    for i in ChooseCoach.objects.filter(teacher=user, time_out=False).all():
        i.drop_class = 'teacher leave'
        i.teacher_leave = True
        i.save()
    try:
        if teacher_leave.objects.create(teacher=user, date=timezone.now().date()):
            raise django.db.utils.IntegrityError
        teacher_leave.objects.create(teacher=user)
    except django.db.utils.IntegrityError:
        return HttpResponse('<script>alert("Ask for leave already!"); window.history.go(-1)</script>')

    return HttpResponse('<script>alert("leave a successful"); window.history.go(-1)</script>')


def cancel_exaln(request):
    ExaminationForPeople.objects.filter(student=request.user, exaln__id=request.GET.get('id')).delete()
    return HttpResponse('<script>alert("cancel a successful"); window.history.go(-1)</script>')
